package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.WmNewsAuthPageDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.wemedia.dtos.WmAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmNewsVO;
import com.heima.utils.thread.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Transactional
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmUserService wmUserService;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsTaskService wmNewsTaskService;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 后台查看文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAuthList(WmNewsAuthPageDto dto) {
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //记录当前页
        int currentPage = dto.getPage();

        //2.分页查询+count查询
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        List<WmNewsAuthPageDto> listAndPage = wmNewsMapper.findListAndPage(dto);
        int count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(currentPage, dto.getSize(), count);
        responseResult.setData(listAndPage);
        return responseResult;
    }

    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //1. 校验参数
        if (dto == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        dto.checkParam();

        //2. 构建分页条件构造器
        Page page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery();
        //2.1 匹配状态
        if (dto.getStatus() != null)
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        //2.2 匹配频道id
        if (dto.getChannelId() != null)
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        //2.3 匹配关键字
        if (dto.getKeyword() != null)
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        //2.4 匹配开始结束时间
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null)
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());

        //3. 查询数据库
        page(page, wrapper);

        //4. 封装结果返回
        PageResponseResult result = new PageResponseResult((int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal());
        result.setCode(AppHttpCodeEnum.SUCCESS.getCode());
        result.setErrorMessage(AppHttpCodeEnum.SUCCESS.getErrorMessage());
        result.setData(page.getRecords());

        return result;

    }

    /**
     * 文章的上下架
     *
     * @param dto
     * @return
     */
    public ResponseResult downOrUp(WmNewsDto dto) {

        //1.参数校验
        if (dto.getId() == null || dto.getEnable() == null || (dto.getEnable() != 0 && dto.getEnable() != 1)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //3.查询文章是否发布已上架
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态,不能上下架");
        }

        //4.修改文章enable
        update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable, dto.getEnable()).eq(WmNews::getId, dto.getId()));

        //5.发送消息,通知article端修改文章配置
        if (wmNews.getArticleId() != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("articleId", wmNews.getArticleId());
            map.put("enable", dto.getEnable());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 发布文章或保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //参数校验
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //数据处理 -- 新增/修改文章共有业务的数据处理
        WmNews wmNews = new WmNews();
        //属性复制
        BeanUtils.copyProperties(dto, wmNews);
        //封面图片images
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String images = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(images);
        }
        //文章封面图片布局或者说显示样式 type
        if (dto.getType() == -1) {
            wmNews.setType(null);   //针对-1自动,先置为null,后续处理
        }

        //1.根据id判断,新增/修改文章
        saveOrUpdateNews(wmNews);
        //2.判断是否为草稿,是草稿就直接返回结果,流程结束
        if (dto.getStatus() == 0) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //3.不是草稿,需要处理内容图片和文章的关联关系
        //提取文章内容中的所有图片
        List<String> imageUrls = parseImageURL(dto.getContent());
        saveRelationWithContentImage(imageUrls, wmNews.getId());

        //4.不是草稿,需要处理封面图片和文章的关联关系
        saveRelationWithCoverImage(dto, wmNews, imageUrls);

        //5.延迟任务,审核
        wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime());


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /*保存封面图片和文章关系
     * 核心功能1:
     * 如果封面模式为自动,需要按照规则匹配对应的到底是单图还是多图,还是无图,匹配规则:
     * a.如果内容图片的数量>=1&&<3,单图模式 setType(1)
     * b.如果内容图片数量>=3 :多图模式,setType(3)
     * c.如果内容图片数量==0,无图模式 srtType(0)
     *
     * 核心功能2:
     * 保存封面图片和文章的关联关系
     * */

    private void saveRelationWithCoverImage(WmNewsDto dto, WmNews wmNews, List<String> imageUrls) {
        //拿到前端传来的封面图片数据
        List<String> images = dto.getImages();

        //处理封面图片模式为自动的情况
        if (dto.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO) {
            if (imageUrls.size() >= 3) {
                //多图
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                //将内容图片中的前三张截取作为封面照片
                images = imageUrls.stream().limit(3).collect(Collectors.toList());
            } else if (imageUrls.size() >= 1 && imageUrls.size() < 3) {
                //单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                //将内容图片中的第一张截取作为封面图片
                images = imageUrls.stream().limit(1).collect(Collectors.toList());
            } else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            //内容图片处理,之前是封面图片处理重新set
            if (images != null && images.size() > 0) {
                wmNews.setImages(StringUtils.join(images, ","));
            }
            //修改数据库中文章的封面类型
            updateById(wmNews);
        }

        //保存封面图片和文章的关联关系
        if (images != null && images.size() > 0) {
            saveRelationWithImage(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }

    }


    //保存文章与内容图片关系
    private void saveRelationWithContentImage(List<String> imageUrls, Integer id) {
        saveRelationWithImage(imageUrls, id, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    //保存文章与内容图片的关联关系
    private void saveRelationWithImage(List<String> imageUrls, Integer newsId, Short type) {
        //参数校验
        if (imageUrls != null && newsId != null) {
            //根据图片url查询素材表,拿到图片id
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageUrls));
            List<Integer> materialIds = wmMaterials.stream().map(wm -> wm.getId()).collect(Collectors.toList());
            if (materialIds.size() != imageUrls.size()) {
                //如果数据库中图片数量与内容中提取到的数量不对应,说明内容图片有脏数据
                //此时需要排除异常,将整个业务回滚
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }

            //保存内容图片素材与文章的关联关系
            wmNewsMaterialMapper.saveRelations(materialIds, newsId, type);

        }
    }


    //新增或修改文章
    private void saveOrUpdateNews(WmNews wmNews) {
        //设置提交时间为当前时间
        wmNews.setSubmitedTime(new Date());
        if (wmNews.getId() != null) {
            //修改文章
            //先删除文章与素材的关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        } else {
            //新增文章
            //处理数据:userId,createTime,submitedTime
            wmNews.setUserId(WmThreadLocalUtils.get());
            wmNews.setCreatedTime(new Date());
            save(wmNews);
        }

    }


    /*提取文章内容中的图片*/
    private List<String> parseImageURL(String content) {
        JSONArray jsonArray = JSON.parseArray(content);
        List<String> list = new ArrayList<>();
        //遍历集合,取出每一个数据
        for (Object json : jsonArray) {
            JSONObject jsonObject = JSON.parseObject(json.toString());
            //判断type是否为image
            if (jsonObject.get("type").equals("image")) {
                //是image,则取当前json的value
                String imageURL = jsonObject.get("value").toString();
                list.add(imageURL);
            }
        }

        return list;
    }

    /**
     * 管理端查看文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult one_vo(Integer id) {
        //1、参数校验
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2、业务处理
        //2.1、得到文章详情
        WmNews wmNews = getById(id);
        //2.2、得到作者信息
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());
        //2.3、创建返回对象，并完善属性
        WmNewsVO adminArticleVO = new WmNewsVO();
        BeanUtils.copyProperties(wmNews, adminArticleVO);
        adminArticleVO.setAuthorName(wmUser.getName());
        //3、返回响应结果
        return ResponseResult.okResult(adminArticleVO);
    }

    /**
     * 人工审核文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authFailOrPass(WmAuthDto dto) {
        //1、参数校验
        if (dto == null || dto.getId() == null || dto.getStatus() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2、业务处理
        //2.1、通过，创建app端的文章信息 更新自媒体文章的状态为9
        if (dto.getStatus().equals(WemediaConstants.ARTIFICIAL_PASS)) {
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getStatus,WemediaConstants.PASS));
            //先获取文章对象
            WmNews wmNews = getById(dto.getId());
            //添加延迟任务，异步执行
            wmNewsTaskService.addNewsToTask(wmNews.getId(),wmNews.getPublishTime());
            //返回响应结果
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        if (dto.getStatus().equals(WemediaConstants.ARTIFICIAL_NOT_PASS)) {
            //2.2、驳回，添加理由，修改文章的状态为2
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
                    .set(WmNews::getStatus,WemediaConstants.ARTIFICIAL_NOT_PASS)
                    .set(WmNews::getReason,dto.getMsg()));
        }
        //3、返回响应结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
